package com.atguigu.zy.interview.juc.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Phone implements Runnable {
    public synchronized void sendSms() throws Exception {
        System.out.println(Thread.currentThread().getName() + "\t invoke sendSMS");
        sendEmail();
    }

    public synchronized void sendEmail() throws Exception {
        System.out.println(Thread.currentThread().getName() + "\t invoke sendEmail");
    }


    //======================================

    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        get();
    }

    public void get() {
        /** 
         * 1、面试问，加两把锁可不可以，只要锁匹配都可以，如果不匹配，比如加两把锁，释放一把锁，程序就会一直运行
         */
        //lock.lock();
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t invoke get()");
            set();
        } finally {
            //lock.unlock();
            lock.unlock();
        }
    }

    public void set() {
       lock.lock();
       try {
           System.out.println(Thread.currentThread().getName() + "\t invoke set()");
       }finally {
           lock.unlock();
       }
    }
}

/**
 * Description:
 * 可重入锁(也叫做递归锁)
 * 指的是同一先生外层函数获得锁后,内层敌对函数任然能获取该锁的代码
 * 在同一线程外外层方法获取锁的时候,在进入内层方法会自动获取锁
 * <p>
 * 也就是说,线程可以进入任何一个它已经拥有锁的所同步的代码块
 *
 * @author veliger@163.com
 * @date 2019-04-12 23:36
 **/
public class ReenterLockDemo {


    /**
     * case one   synchronize是一个典型的可重入锁
     * t1 sendSms    t1线程外层方法获取锁的时候
     * t1 sendEmail  t1在进入内层方法会自动获取锁
     * t2 sendSms
     * t2 sendEmail
     * @param args
     */
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(() -> {
            try {
                phone.sendSms();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, "t1").start();


        new Thread(() -> {
            try {
                phone.sendSms();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t2").start();


        //空格4行
        //暂停一会儿线程
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
        System.out.println();

    /**
     * 1、 case two  ReentrantLock  是一个典型的可重入锁
     */
        Thread t3 = new Thread(phone,"t3");
        Thread t4 = new Thread(phone,"t4");
        t3.start();
        t4.start();
    }
}
 
 
